package com.tuling.signalling.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.LinkedHashMap;
import java.util.function.Supplier;

public class WebsocketServer {


    private Logger logger;

    private ServerBootstrap bootstrap;

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;

    private int WORK_THREAD = 8;

    private boolean logOpen = true;

    private String logLevel = "DEBUG";

    private int port;

    private Channel channel;

    public WebsocketServer(int port) {
        this(port, WebsocketServer.class);
    }

    public WebsocketServer(int port, Class logName) {
        this.port = port;
        this.logger = LoggerFactory.getLogger(logName);
    }

    public void setLogOpen(boolean logOpen) {
        this.logOpen = logOpen;
    }

    private LinkedHashMap<String, Supplier<ChannelHandler>> handlerChain = new LinkedHashMap<>();

    public void addLastChannel(String handlerName, Supplier<ChannelHandler> handlerSupplier) {
        handlerChain.put(handlerName, handlerSupplier);
    }

    public void start() {
        bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("boss"));
        workerGroup = new NioEventLoopGroup(WORK_THREAD, new DefaultThreadFactory("worker"));
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class)
                .childHandler(new NioChannelInitializer());
        ChannelFuture future = bootstrap.bind(new InetSocketAddress(port));
        logger.info("Socket Server started on port(s):{} (socket)", port);
        try {
            channel = future.sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void doClose() {
        channel.close();
        try {
            bossGroup.shutdownGracefully().sync();
            bossGroup.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public class NioChannelInitializer extends ChannelInitializer<SocketChannel> {


        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (logOpen) {
                pipeline.addLast("logging", new LoggingHandler(logLevel));
            }
            pipeline.addLast("http-codec", new HttpServerCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(1 << 16));
            pipeline.addLast("http-chunked", new ChunkedWriteHandler());
            if (!handlerChain.isEmpty()) {
                handlerChain.forEach((key, supplier) -> {
                    pipeline.addLast(key, supplier.get());
                });
            }
        }

    }

}
